package com.zwb.qwflow.controller;

import cn.hutool.core.util.BooleanUtil;
import com.alibaba.fastjson.JSONObject;
import com.zwb.qwflow.constant.CommonConstant;
import com.zwb.qwflow.domin.param.CommitApprovalApplyParam;
import com.zwb.qwflow.domin.param.SearchApprovalVo;
import com.zwb.qwflow.result.AccessTokenResult;
import com.zwb.qwflow.util.qw.aes.AesException;
import com.zwb.qwflow.util.qw.aes.WXBizMsgCrypt;
import jdk.internal.org.xml.sax.SAXException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/send")
public class SendQwController {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RestTemplate restTemplate;


    @RequestMapping(value = "/sendQw")
    public String sendQw() {
        return "ok";
    }


    public String getToken() {

        System.out.println("get token ............");

        if (BooleanUtil.isTrue(stringRedisTemplate.hasKey(CommonConstant.ACCESSTOKEN))) {
            return stringRedisTemplate.opsForValue().get(CommonConstant.ACCESSTOKEN);
        }

        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRET"
                .replace("ID", CommonConstant.CORPID).replace("SECRET", CommonConstant.CORPSECRET);
        try {
            ResponseEntity<AccessTokenResult> responseEntity = restTemplate.getForEntity(url, AccessTokenResult.class);
            System.out.println("调用结果：" + responseEntity);
            if (responseEntity.getStatusCode() == HttpStatus.OK) {
                AccessTokenResult ac = responseEntity.getBody();
                assert ac != null;
                if (ac.getErrcode() == 0) {
                    stringRedisTemplate.opsForValue().set(CommonConstant.ACCESSTOKEN, ac.getAccess_token(), 2, TimeUnit.HOURS);
                    return ac.getAccess_token();
                }
            }
        } catch (RuntimeException e) {
            throw new RuntimeException("获取微信token失败", e);
        }

        throw new RuntimeException("获取微信token失败");

    }

    /**
     * 获取审批模板详情
     *
     * @param templateId id
     */
    public String getTemplateDetail(String templateId) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/oa/gettemplatedetail?access_token=ACCESS_TOKEN"
                .replace("ACCESS_TOKEN", getToken());
        Map<String, String> reqParam = new HashMap<>();
        reqParam.put("template_id", templateId);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, reqParam, String.class);
        System.out.println("调用结果：" + responseEntity);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            return responseEntity.getBody();
        }
        return "失败";
    }

    /**
     * 读取成员
     *
     * @param userId userId
     * @return 编号
     */
    public String getUserDetail(String userId) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=USERID"
                .replace("ACCESS_TOKEN", getToken()).replace("USERID", userId);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        System.out.println("调用结果：" + responseEntity);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            return responseEntity.getBody();
        }
        throw new RuntimeException("读取成员失败请求访问失败");
    }

    public String commitApprovalApply(CommitApprovalApplyParam param) {

        String url = "https://qyapi.weixin.qq.com/cgi-bin/oa/applyevent?access_token=ACCESS_TOKEN"
                .replace("ACCESS_TOKEN", getToken());

        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, param, JSONObject.class);
        System.out.println("调用结果：" + responseEntity);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            JSONObject body = responseEntity.getBody();
            if (body.getInteger("errcode") == 0) {
                return body.getString("sp_no");
            }
            throw new RuntimeException("提交审批流程失败：" + body.getString("errmsg"));
        }
        throw new RuntimeException("提交审批流程请求访问失败");
    }

    public JSONObject searchApprovalList(SearchApprovalVo searchApprovalVo) {

        String url = "https://qyapi.weixin.qq.com/cgi-bin/oa/getapprovalinfo?access_token=ACCESS_TOKEN"
                .replace("ACCESS_TOKEN", getToken());

        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, searchApprovalVo, JSONObject.class);
        System.out.println("调用结果：" + responseEntity);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            return responseEntity.getBody();
        }
        throw new RuntimeException("提交审批流程请求访问失败");
    }

    public JSONObject getApprovalDetail(String spNo){

        String url = "https://qyapi.weixin.qq.com/cgi-bin/oa/getapprovaldetail?access_token=ACCESS_TOKEN"
                .replace("ACCESS_TOKEN", getToken());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sp_no",spNo);

        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, jsonObject, JSONObject.class);
        System.out.println("调用结果：" + responseEntity);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            return responseEntity.getBody();
        }
        throw new RuntimeException("提交审批流程请求访问失败");
    }


    @GetMapping("/feedbackFromWx")
    public String feedbackFromWxVerifyURL(String msg_signature, String timestamp, String nonce, String echostr) throws AesException {

        System.out.printf("-------feedbackFromWx ------ msg_signature:%s, Long timestamp:%s, String nonce:%s, String echostr:%s%n",
                msg_signature, timestamp, nonce, echostr);
        String sToken = "zwb6666";
        String sEncodingAESKey = "9QVSyFkf3IvZrlcV3WVxhLGMWZGMzj3SDmsWDQqYGBL";

        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, CommonConstant.CORPID);
        String sMsg = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr);
        System.out.printf("sMsg:%s%n", sMsg);
        return sMsg;
    }

    @PostMapping("/feedbackFromWx")
    public String feedbackFromWxData(String msg_signature, String timestamp, String nonce, @RequestBody String data)
            throws AesException, ParserConfigurationException, IOException, SAXException, org.xml.sax.SAXException {
        System.out.println(String.format("-------feedbackFromWx ------ msg_signature:%s, Long timestamp:%s, String nonce:%s, String data:%s",
                msg_signature, timestamp, nonce, data));
        String sToken = "zwb6666";
        String sEncodingAESKey = "9QVSyFkf3IvZrlcV3WVxhLGMWZGMzj3SDmsWDQqYGBL";
        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, CommonConstant.CORPID);
        String sMsg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, data);
        System.out.println("sMsg:"+sMsg);

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        StringReader sr = new StringReader(sMsg);
        InputSource is = new InputSource(sr);
        Document document = db.parse(is);

        Element root = document.getDocumentElement();

        System.out.println("AgentID:"+root.getElementsByTagName("AgentID").item(0).getTextContent());
        System.out.println("SpNo:"+root.getElementsByTagName("SpNo").item(0).getTextContent());
        System.out.println("SpStatus:"+root.getElementsByTagName("SpStatus").item(0).getTextContent());
        System.out.println("TemplateId:"+root.getElementsByTagName("TemplateId").item(0).getTextContent());

        return sMsg;
    }




}
